package com.example.demo.thread;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class TestForkJoin {
    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();

        Instant start = Instant.now();

    }


}

class ForkjoinDemo extends RecursiveTask<Long> {
    private long start;
    private long end;
    public static final int BORDER = 100000;

    public ForkjoinDemo(long start, long end) {
        this.start = start;
        this.end = end;
    }

    protected Long compute() {
        long length = end - start;

        if (length <= BORDER) {
            long sum = 0;
            for (long i = start; i < end; i++) {
                sum += i;
            }
            return sum;
        } else {
            long middle = (end - start) / 2;
            ForkjoinDemo left = new ForkjoinDemo(start, middle);
            left.fork();
            ForkjoinDemo right = new ForkjoinDemo(middle + 1, end);
            right.fork();
            return left.join() + right.join();
        }

    }

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();
        Instant start = Instant.now();
        ForkjoinDemo forkjoinDemo = new ForkjoinDemo(0, 10000);

        pool.invoke(forkjoinDemo);
        Instant end = Instant.now();
        System.out.println("耗费时间=" + Duration.between(start, end));
    }
}